<template>
  <el-dialog
          :model-value="dialogVisible"
          :title="dialogTitle"
          :before-close="handleCancelDialog"
          width="70%"
          top="5vh"
  >
    <el-card>
      <el-row>
        <el-col :span="24">
          <el-input placeholder="请输入介质名称" size="small" v-model="queryList.keyword" class="input-w" />
          <el-select
                  placeholder="选择画幅类型"
                  v-model="queryList.layout"
                  clearable
                  @change="handlerFilter"
                  class="select-w ml10" size="small">
            <el-option
                    v-for="layout in layoutList"
                    :key="layout.layoutid"
                    :label="layout.layoutname"
                    :value="layout.layoutid"
            ></el-option>
          </el-select>
          <el-select
                  placeholder="全部部门"
                  v-model="queryList.groupid"
                  clearable
                  @change="handlerFilter"
                  class="select-w ml10" size="small">
            <el-option v-for="group in groupList"
                       :key="group.groupid"
                       :label="group.name"
                       :value="group.groupid"
            ></el-option>
          </el-select>
          <el-button size="small" class="ml10" type="primary" @click="handlerFilter">
            <el-icon>
              <search />
            </el-icon>
            搜索
          </el-button>
        </el-col>
        <el-col :span="24" class="mt10">
          <el-table :data="tableData.listData"
                    ref="materialTableRef"
                    v-loading="isloading"
                    border
                    @row-click="handleClickRow"
                    @select="handleSelect"
                    @select-all="handleSelectAll"
                    max-height="330px"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="预览" width="60" v-if="materialtype == 'image'">
              <template #default="{row, $index}">
                <span @click.stop>
                  <el-image
                          :preview-src-list="imageSrcList"
                          :initial-index="$index"
                          :src="getImageUrl(row, 2)"
                  />
                </span>
              </template>
            </el-table-column>
            <el-table-column label="介质名称" prop="name" show-overflow-tooltip>
              <template #default="{row}">
                <span v-if="materialtype == 'image'">{{row.name}}</span>
                <a href="javascript:;" @click.stop="handleVideoPlay(row)" v-else>
                  <el-icon>
                    <video-play />
                  </el-icon>
                  {{row.name}}
                </a>
              </template>
            </el-table-column>
            <el-table-column label="文件大小">
              <template #default="{row}">
                <span v-if="row.extends && row.extends.size">{{formatSize(row.extends.size)}}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="分辨率">
              <template #default="{row}">
                <span v-if="row.extends && row.extends.width && row.extends.height">{{row.extends.width + ' * ' + row.extends.height}}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column label="画幅类型">
              <template #default="{row}">
                {{getLayoutName(row.layout)}}
              </template>
            </el-table-column>
            <el-table-column label="所属部门">
              <template #default="{row}">
                {{groupOptions[row.groupid]}}
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row class="mt10">
        <el-col :span="24">
          <table-pagination
                  :queryList="queryList"
                  :total="tableData.total"
                  @pagination="getDataList"
          />
        </el-col>
      </el-row>
    </el-card>
    <template #footer>
      <div align="center">
        <el-button type="default" size="mini" @click="handleCancelDialog">取消</el-button>
        <el-button type="primary" size="mini" @click="handlePackageRelMaterial">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
  import {toRef, reactive, ref, nextTick} from 'vue'
  import {getImages} from "@/api/media/image";
  import {layoutList, formatSize, getLayoutName, getImageUrl} from "@/utils/usage-config";
  import { Search, VideoPlay } from "@element-plus/icons"
  import {getSubRefGroup} from "@/api/group";
  import TablePagination from "@/views/public/TablePagination";
  import {getVideos} from "@/api/media/video";
  import {packageRelImage, packageRelVideo} from "@/api/package/material";
  import {ElMessage} from 'element-plus'

  export default {
    name: "AddMaterial",
    components: {TablePagination, Search, VideoPlay},
    props: {
      dialogVisible: {
        type: Boolean,
        default: false
      },
      dialogTitle: {
        type: String,
        default: '添加图片素材'
      },
      materialType: {
        type: String,
        default: 'image'
      },
      dialogFormData: {
        type: Object,
        default() {
          return {}
        }
      }
    },
    emits: ['handleCancelDialog', 'reloadData', 'handleVideoPlay'],
    setup(props, context) {
      const materialtype = toRef(props, 'materialType')
      const formData = toRef(props, 'dialogFormData')
      const queryList = reactive({
        page: 1,
        pagesize: 25,
        keyword: undefined,
        groupid: undefined,
        layout: undefined
      })
      const tableData = reactive({
        total: 0,
        listData: []
      })
      const groupList = ref([])
      const groupOptions = reactive({})
      const isloading = ref(false)
      const imageSrcList = ref([])
      const materialTableRef = ref(null)

      /** 获取部门列表 **/
      const getGroupList = () => {
        getSubRefGroup().then(response => {
          groupList.value = response.data
          groupList.value.forEach(group => {
            groupOptions[group.groupid] = group.name
          })
        })
      }
      /** 获取素材列表 **/
      const getDataList = () => {
        isloading.value = true
        if (materialtype.value == 'image') {
          getImages(queryList).then(response => {
            isloading.value = false
            const {total, list} = response.data
            tableData.total = total
            tableData.listData = list
            imageSrcList.value = []
            nextTick(() => {
              tableData.listData.forEach(row => {
                imageSrcList.value.push(getImageUrl(row, 1))
              })
            })
          })
        } else {
          getVideos(queryList).then(response => {
            isloading.value = false
            const {total, list} = response.data
            tableData.total = total
            tableData.listData = list
          })
        }
      }
      /** 搜索素材 **/
      const handlerFilter = () => {
        queryList.page = 1
        getDataList()
      }

      /** 点击table行 **/
      const handleClickRow = (row) => {
        getSelectedMaterialIds(row)
      }
      /** 单个选择 **/
      const handleSelect = (selection, row) => {
        getSelectedMaterialIds(row)
      }
      /** 全选 **/
      const handleSelectAll = (selection) => {
        if (selection.length > 0) {
          selection.forEach(row => {
            if (materialtype.value == 'image') {
              if (!formData.value.imgids.includes(row.imgid)) {
                formData.value.imgids.push(row.imgid)
              }
            } else {
              if (!formData.value.videoid.includes(row.videoid)) {
                formData.value.videoids.push(row.videoid)
              }
            }
          })
        } else {
          formData.value.imgids = []
          formData.value.videoids = []
        }
      }
      /** 获取选择的素材ID **/
      const getSelectedMaterialIds = (row) => {
        if (materialtype.value == 'image') {
          if (formData.value.imgids.includes(row.imgid)) {
            const index = formData.value.imgids.findIndex(d => d == row.imgid)
            formData.value.imgids.splice(index, 1)
            materialTableRef.value.toggleRowSelection(row, false)
          } else {
            formData.value.imgids.push(row.imgid)
            materialTableRef.value.toggleRowSelection(row, true)
          }
        } else {
          if (formData.value.videoids.includes(row.videoid)) {
            const index = formData.value.videoids.findIndex(d => d == row.videoid)
            formData.value.videoids.splice(index, 1)
            materialTableRef.value.toggleRowSelection(row, false)
          } else {
            formData.value.videoids.push(row.videoid)
            materialTableRef.value.toggleRowSelection(row, true)
          }
        }
      }

      /** 关闭弹框 **/
      const handleCancelDialog = () => {
        context.emit('handleCancelDialog')
      }
      /** 关联素材 **/
      const handlePackageRelMaterial = () => {
        if (materialtype.value == 'image') {
          if (formData.value.imgids.length <= 0) {
            ElMessage({type: 'warning', message: '请选择要添加的图片素材', duration: 2000})
          } else {
            packageRelImage(formData.value).then(response => {
              if (response.errcode == 0) {
                ElMessage({type: 'success', message: response.msg, duration: 2000})
                handleCancelDialog()
                context.emit('reloadData')
              }
            })
          }
        } else {
          if (formData.value.videoids.length <= 0) {
            ElMessage({type: 'warning', message: '请选择要添加的视频素材', duration: 2000})
          } else {
            packageRelVideo(formData.value).then(response => {
              ElMessage({type: 'success', message: response.msg, duration: 2000})
              handleCancelDialog()
              context.emit('reloadData')
            })
          }
        }
      }
      /** 播放视频 **/
      const handleVideoPlay = (row) => {
        context.emit('handleVideoPlay', row)
      }

      const init = () => {
        getGroupList()
        getDataList()
      }

      return {
        handleCancelDialog,
        materialtype,
        queryList,
        init,
        layoutList,
        groupOptions,
        groupList,
        isloading,
        imageSrcList,
        tableData,
        getDataList,
        formatSize,
        getLayoutName,
        handlerFilter,
        getImageUrl,
        handlePackageRelMaterial,
        handleClickRow,
        handleSelect,
        handleSelectAll,
        materialTableRef,
        handleVideoPlay
      }
    }
  }
</script>

<style scoped>

</style>
